package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.xuecheng.base.exception.XueChengException;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author Linzkr
 * @description: TODO  账号名密码认证的实现
 * @date 2023/2/1 10:07
 */
@Service("password_auth_service")
@Slf4j
public class PasswordAuthServiceImpl implements AuthService {
    @Autowired
    XcUserMapper xcUserMapper ;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    CheckCodeClient checkCodeClient;
    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {
//        校验验证码
//        远程调用 请求验证码服务
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
//        if (StringUtils.isBlank(checkcode)||StringUtils.isBlank(checkcodekey)){
//            XueChengException.cast("输入的验证码为空");
//        }
//        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
//        if (verify==null||!verify){
//            XueChengException.cast("输入的验证码不正确");
//        }

        String username = authParamsDto.getUsername();
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
        if (xcUser==null){
            XueChengException.cast("该用户不存在");
        }
//        数据库中的密文密码
        String passwordFromDB = xcUser.getPassword();
//        用户输入的明文密码
        String passwordFromInPut = authParamsDto.getPassword();
//        比对
        boolean matchesFlag = passwordEncoder.matches(passwordFromInPut, passwordFromDB);
        if (!matchesFlag){
            XueChengException.cast("用户名或密码错误");
        }
        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);
        return xcUserExt;
    }
}
